<template>
  <div id="materail-box" ref="materailBox">
    <h1 class="title">素材管理</h1>
    <div class="main-cont">
      <v-toolbar @click="handleToolClick" :buttonsObj="buttonsObj"></v-toolbar>
    <el-container>
      <el-main>
        <input type="file" @change="uploadImg" v-show="false" id="imgUp">
        <el-table  :data="tableData" :height="height">
          <el-table-column label="文件名">
            <template slot-scope="scope">
              <img src="../../../../images/wenjianjia.png" v-if="scope.row.IsDir"/>
              <img :src="handleImageUrl(scope.row)" v-if="!scope.row.IsDir"/>
              <a @click="getMaterialFile(scope.row.IsDir,scope.row.Url!=undefined?scope.row.Url:'',scope.row.Name)">{{scope.row.Name}}</a>
            </template>
          </el-table-column>
          <el-table-column label="大小">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.Size) }}
            </template>
          </el-table-column>
          <el-table-column label="创建日期">
            <template slot-scope="scope">
              {{ getDateTime(scope.row.CreateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="mini" v-if="!scope.row.IsDir" @click="delMaterialFile(scope.row.Url!=undefined?scope.row.Url:'',scope.row.Name,!scope.row.IsDir)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    </div>
    <v-dialog title="新建文件夹" :isVisible="dialogFormVisible" @close="closeDialog">
      <template slot="dialog-cont">
        <el-form :model="folderForm" :rules="folderRules" ref="folderForm" class="dialog-main dialogForm">
          <el-form-item label="文件夹名称" prop="Name">
            <el-input v-model="folderForm.Name" autocomplete="off"/>
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-btns">
        <div class="form-buttons">
          <el-button @click="resetForm" size="mini">重置</el-button>
          <el-button @click="closeDialog" size="mini">关闭</el-button>
          <el-button type="primary" @click="addFolder" size="mini">确定</el-button>
        </div>
      </template>
    </v-dialog>
  </div>
</template>
<script>
  import VToolbar from '../../comm/iToolbar/iToolbar'
  import VDialog from '../../comm/iDialog/iDialog'
  import api from '../../../../api/url'
  import ajax from '../../../../api/ajax/ajax'

  export default {
    components: {
      VToolbar,
      VDialog
    },
    data () {
      return {
        tableData: [],
        height: null,
        buttonsObj: [
          {text: '上传', oprType: 'addPic'},
          {text: '新建文件夹', oprType: 'addDir'},
          {text: '全部文件', oprType: 'fileList'}
        ],
        dialogFormVisible: false,
        formLabelWidth: '120px',
        folderForm: {
          Name: ''
        },
        folderData: {},
        folderRules: {
          Name: [
            { required: true, message: '请输入文件夹名称', trigger: 'blur' }
          ]
        },
        // 存储当前文件夹路径
        url: '',
        files: ''
      }
    },
    methods: {
      //  文件/文件夹 点击事件处理
      getMaterialFile (isDir, Url, Name) {
        var url = Url + '/' + Name
        this.url = url
        if (isDir) {
          this.$options.methods.getMaterialFileList.bind(this)(url, isDir)
        }
      },
      // 进入文件夹
      getMaterialFileList (url, isDir) {
        ajax.get(api.QUERY_MATERIAL_FILE, {url: url}).then(res => {
          this.tableData = res
        }).catch(() => {})
      },
      // 获取 全部文件
      getMaterialFileListAll () {
        this.url = ''
        ajax.get(api.QUERY_MATERIAL_FILE).then(res => {
          this.tableData = res
        })
      },
      // 删除文件
      delMaterialFile (Url, Name, isDir) {
        this.$confirm('确定要删除该素材吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var formData = new FormData()
          formData.append('url', Url + '/' + Name)
          ajax.post(api.DELETE_FILEDEL_METARIALS, formData).then(res => {
            if (res.Code === 0) {
              this.$message({
                type: 'success',
                message: '文件删除成功'
              })
            }
            this.getMaterialFileList(Url, isDir)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 打开上传图片的弹窗
      addPic () {
        document.getElementById('imgUp').click()
      },
      // 添加文件夹
      addDir () {
        this.dialogFormVisible = true
      },
      // 上传图片
      uploadImg (e) {
        let oFile = document.getElementById('imgUp')
        let fileName = oFile.files[0].name
        if (/\s+/g.test(fileName)) {
          this.$message({
            message: '上传图片的名称不应该包含空格',
            type: 'error'
          })
          return false
        }
        let formData = new FormData()
        formData.append('upload', oFile.files[0])
        formData.append('url', this.url)
        ajax.post(api.ADD_FILE_UPLOAD_METARIALS, formData).then(res => {
          if (res.Code === 0) {
            this.$message({
              type: 'success',
              message: '图片上传成功'
            })
          }
          this.getMaterialFileList(this.url, true)
        })
      },
      // 新建文件夹-提交表单
      addFolder () {
        this.$refs.folderForm.validate((valid) => {
          if (valid) {
            let postData = {
              Url: this.url,
              Folder: this.folderForm.Name
            }
            ajax.get(api.ADD_MATERIAL_FOLDER_CREATE, postData).then(res => {
              if (res.Code === 0) {
                this.$message({
                  type: 'success',
                  message: '新建成功'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: '新建失败'
                })
              }
              this.dialogFormVisible = false
              this.getMaterialFileList(this.url, true)
            }).catch((err) => {
              console.info(err)
            })
          } else {
            return false
          }
        })
      },
      // 初始化表单
      initForm () {
        this.$refs.folderForm.resetFields()
        this.url = ''
        this.folderForm = {
          Name: ''
        }
      },
      // 重置
      resetForm () {
        this.initForm()
        if (this.editMode === 'EDIT') {
          this.folderForm = {...this.folderData}
        }
      },
      // 关闭弹窗
      closeDialog () {
        this.$refs.folderForm.resetFields()
        this.url = ''
        this.folderForm = {
          Name: ''
        }
        this.dialogFormVisible = false
      },
      // 文件大小处理
      formatFileSize (fileSize) {
        if (fileSize === 0) {
          return '-'
        } else if (fileSize < 1024) {
          return fileSize + 'B'
        } else if (fileSize < (1024 * 1024)) {
          return (fileSize / 1024).toFixed(2) + 'KB'
        } else if (fileSize < (1024 * 1024 * 1024)) {
          return (fileSize / (1024 * 1024)).toFixed(2) + 'MB'
        } else {
          return (fileSize / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
        }
      },
      // 转换日期格式
      getDateTime (time) {
        let date = new Date(time * 1000).toLocaleString().split(' ')[0]
        return date
      },
      // 工具栏操作
      handleToolClick (opt) {
        switch (opt) {
          case 'addPic':
            this.addPic()
                break
          case 'addDir':
            this.addDir()
            break
          case 'fileList':
            this.getMaterialFileListAll()
            break
          default:
            break
        }
      },
      // 处理图片显示
      handleImageUrl (data) {
        let zipType = ['zip', 'rar', 'jar', '7z', 'tar', 'gz']
        let imageType = ['png', 'jpg', 'gif', 'jpeg']
        let suffix = data.Name.split('.').pop()
        if (imageType.indexOf(suffix) !== -1) {
          return data.Root + (data.Url !== undefined ? data.Url : '') + '/' + data.Name
        } else if (zipType.indexOf(suffix) !== -1) {
          return '/static/img/zip.png'
        } else {
          return '/static/img/image.png'
        }
      }
    },
    created () {
      this.$nextTick(() => {
        this.height = this.$refs.materailBox.offsetHeight - 138 - 32
      })
      ajax.get(api.QUERY_MATERIAL_FILE).then(res => {
        this.tableData = res
      })
    }
  }
</script>
<style lang="stylus">
  #materail-box
    height 100%
    overflow hidden
    .checked
      display block
      margin-left 15px
      width 32px
      height 32px
      background url('') no-repeat center center
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
    .mt10
      margin-top 10px
    .main-cont
      padding 10px 0 0 10px
    .el-container
      img
        height:30px;
        width:30px;
    .el-table
      img
        vertical-align middle
      a
        vertical-align middle
</style>
